package com.ruoyi.servie.service.impl;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.ruoyi.common.core.domain.ResultResponse;
import com.ruoyi.common.utils.CreateIdUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.servie.param.WeChatAppletPayParams;
import com.ruoyi.servie.service.IWeChatPayService;
import org.springframework.beans.factory.annotation.Autowired;

public class WeChatPayServiceImpl implements IWeChatPayService {

    @Autowired
    private WxPayConfig wxConfig;

    @Override
    public ResultResponse weChatAppletPayCreateOrder(WeChatAppletPayParams weChatPayParams) throws WxPayException {
        WxPayServiceImpl wxPayService = new WxPayServiceImpl();
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = WxPayUnifiedOrderRequest.newBuilder()
                .body(weChatPayParams.getBody())
                .outTradeNo(weChatPayParams.getOutTradeNo())
                .totalFee(weChatPayParams.getTotalFee())
                .notifyUrl(weChatPayParams.getNotifyUrl())
                .tradeType(weChatPayParams.getTradeType())
                .spbillCreateIp(IpUtils.getHostIp())
                .build();
        //随机字符串，长度要求在32位以内
        wxPayUnifiedOrderRequest.setNonceStr(CreateIdUtils.getRandomStringByLength(27));
        //通过签名算法计算得出的签名并设置Sign值
        wxPayUnifiedOrderRequest.checkAndSign(wxConfig);
        ResultResponse response = new ResultResponse();
        try{
            WxPayMpOrderResult order = wxPayService.createOrder(wxPayUnifiedOrderRequest);
            response.put("appId", order.getAppId());
            response.put("timeStamp", order.getTimeStamp());
            response.put("nonceStr", order.getNonceStr());
            response.put("packageValue", order.getPackageValue());
            response.put("signType", order.getSignType());
            response.put("paySign", order.getPaySign());
            response.put("prepayId", order.getPackageValue().split("=")[1]);
        } catch (Exception e) {
            response.setShuCode("error");
            response.setMsg(e.toString());
        }
        return response;
    }



}
